package com.etooling.framework.controller;

import com.etooling.framework.entity.AttachFile;
import com.etooling.framework.entity.Company;
import com.etooling.framework.entity.FileResource;
import com.etooling.framework.jpa.JpaQueryBuilder;
import com.etooling.framework.jpa.Specifications;
import com.etooling.framework.repository.AttachFileRepository;
import com.etooling.framework.repository.CompanyRepository;
import com.etooling.framework.repository.FileResourceRepository;
import com.etooling.framework.service.FileUploadSaveService;
import com.etooling.framework.svo.ReplyObj;
import com.etooling.framework.utils.VoToPoUtil;
import com.etooling.framework.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;

@RequestMapping(value = "/admin/company")   //请求映射
@Controller  //控制器
@EnableAutoConfiguration   //自动配置
public class CompanyController {
    @Autowired
    CompanyRepository companyRepository;


    @RequestMapping("pageQuery") //查询
    @ResponseBody
    ReplyObj newJpaPageQuery(HttpServletRequest request,
                             @RequestParam(defaultValue = "10", required = false, value = "pageSize") int pageSize, //请求参数
                             @RequestParam(defaultValue = "1", required = false, value = "page") int page,
                             @RequestParam(defaultValue = "", required = false, value = "searchValue") String searchValue,
                             @RequestParam(defaultValue = "", required = false, value = "status") String status
    ) {
        JpaQueryBuilder pb = Specifications.<Company>and();
        if (WebUtils.checkStr(status)) {
            pb.eq("status", status);
        }
        if (WebUtils.checkStr(searchValue)) {
            pb.predicate(Specifications.or()
                    .like("name", "%" + searchValue + "%")
                    .like("orgCode", "%" + searchValue + "%")
                    .build());
        }

        Specification<Company> spec = pb.build();
        Pageable pageable = PageRequest.of(page - 1, pageSize);

        return WebUtils.flushSuccess(companyRepository.findAll(spec, pageable));
    }

    @RequestMapping("add")
    @ResponseBody
    ReplyObj add(HttpServletRequest request, Company vo,
                 @RequestParam(defaultValue = "", required = false, value = "licenseImgFile") String licenseImgFile,
                 @RequestParam(defaultValue = "",required = false,value = "billQrCodeFile")String billQrCodeFile,
                 @RequestParam(defaultValue = "", required = false, value = "logoFileId") String logoFileId


    ) {
        if (WebUtils.checkStr(licenseImgFile)){
            AttachFile licenseFile = attachFileRepository.getOne(licenseImgFile);
            vo.setLicenseImgFile(licenseFile);
        }
        if (WebUtils.checkStr(logoFileId)){
            AttachFile logoFile = attachFileRepository.getOne(logoFileId);
            vo.setLogoImg(logoFile);
        }
        if(WebUtils.checkStr(billQrCodeFile)){
            AttachFile billQrCode = attachFileRepository.getOne(billQrCodeFile);
            vo.setBillQrCode(billQrCode);
        }
        companyRepository.save(vo);
        return WebUtils.flushSuccess();
    }

    @RequestMapping("update")
    @ResponseBody
    ReplyObj update(HttpServletRequest request, Company vo, @RequestParam(defaultValue = "",required = false,value = "billQrCodeFile")String billQrCodeFile
    ) {
        try {
            //vo界面传入的对象，po是数据的对象，有很多时候有些属性页面传过来的东西是不全，或不能修改的，如修改时间，这时就是通过第三个属性，忽略一些属性
            Company po = companyRepository.getOne(vo.getId());
            po.setName(vo.getName());
            po = (Company) VoToPoUtil.copyProperties(po, vo, new String[]{ "licenseImgFile", "createTime"});
            if(WebUtils.checkStr(billQrCodeFile)){
                AttachFile billQrCode = attachFileRepository.getOne(billQrCodeFile);
                vo.setBillQrCode(billQrCode);
            }
            companyRepository.save(vo);
            return WebUtils.flushSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure();
        }
    }

    @Autowired
    AttachFileRepository attachFileRepository;
    @Autowired
    FileResourceRepository fileResourceRepository;

    @RequestMapping("uploadFiles")
    @ResponseBody
    ReplyObj uploadFiles(HttpServletRequest request
    ) {

        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        MultipartFile uploadFile = multiRequest.getFile("uploadFiles");
        if (uploadFile.isEmpty() == false) {
            String originalFilename = uploadFile.getOriginalFilename();
            String compCode = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            Boolean isEncrypt = false;
            try {
                if (WebUtils.checkStr(request.getParameter("isEncrypt"))) {
                    isEncrypt = Boolean.valueOf(request.getParameter("isEncrypt"));
                }
                if (!uploadFile.isEmpty()) {
                    //拿出现在应用的文件存储方式
                    FileResource fileResource = fileResourceRepository.getByApplyResource("七牛存储");
                    String uploadImplClass = fileResource.getImplClassName();
                    FileUploadSaveService fileUploadSaveService = (FileUploadSaveService) Class.forName(String.valueOf(uploadImplClass)).getDeclaredConstructor().newInstance();
                    AttachFile attachFile = fileUploadSaveService.upload(attachFileRepository, uploadFile, fileResource, isEncrypt);
                    return WebUtils.flushObjSuccess(attachFile);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return WebUtils.flushFailure();
            }
        }

        return WebUtils.flushFailure();
    }


    @RequestMapping("uploadLogoFiles")
    @ResponseBody
    ReplyObj uploadLogoFiles(HttpServletRequest request
    ) {

        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        MultipartFile uploadFile = multiRequest.getFile("uploadLogoFiles");
        if (uploadFile.isEmpty() == false) {
            String originalFilename = uploadFile.getOriginalFilename();
            String compCode = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            Boolean isEncrypt = false;
            try {
                if (WebUtils.checkStr(request.getParameter("isEncrypt"))) {
                    isEncrypt = Boolean.valueOf(request.getParameter("isEncrypt"));
                }
                if (!uploadFile.isEmpty()) {
                    //拿出现在应用的文件存储方式
                    FileResource fileResource = fileResourceRepository.getByApplyResource("七牛存储");
                    String uploadImplClass = fileResource.getImplClassName();
                    FileUploadSaveService fileUploadSaveService = (FileUploadSaveService) Class.forName(String.valueOf(uploadImplClass)).getDeclaredConstructor().newInstance();
                    AttachFile attachFile = fileUploadSaveService.upload(attachFileRepository, uploadFile, fileResource, isEncrypt);
                    return WebUtils.flushObjSuccess(attachFile);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return WebUtils.flushFailure();
            }
        }

        return WebUtils.flushFailure();
    }

    @RequestMapping("uploadCode")
    @ResponseBody
    ReplyObj uploadCode(HttpServletRequest request
    ) {

        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        MultipartFile uploadFile = multiRequest.getFile("uploadFiles");
        if (uploadFile.isEmpty() == false) {
            String originalFilename = uploadFile.getOriginalFilename();
            String compCode = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
                Boolean isEncrypt = false;
                try {
                    if (!fileType.equals(".pdf") || !fileType.equals(".PDF")) {
                        if (WebUtils.checkStr(request.getParameter("isEncrypt"))) {
                        isEncrypt = Boolean.valueOf(request.getParameter("isEncrypt"));
                    }
                    if (!uploadFile.isEmpty()) {
                        //拿出现在应用的文件存储方式
                        FileResource fileResource = fileResourceRepository.getByApplyResource("七牛存储");
                        String uploadImplClass = fileResource.getImplClassName();
                        FileUploadSaveService fileUploadSaveService = (FileUploadSaveService) Class.forName(String.valueOf(uploadImplClass)).getDeclaredConstructor().newInstance();
                        AttachFile attachFile = fileUploadSaveService.upload(attachFileRepository, uploadFile, fileResource, isEncrypt);
                        return WebUtils.flushObjSuccess(attachFile);
                    }
                    }else {
                        return WebUtils.flushSuccess("图片只接受pdf/jpg/jpeg/png文件上传");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return WebUtils.flushFailure();
                }
        }

        return WebUtils.flushFailure();
    }

    @RequestMapping("uploadLogo")
    @ResponseBody
    ReplyObj uploadAvatar(HttpServletRequest request
    ) {

        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        MultipartFile uploadFile = multiRequest.getFile("logoFile");
        if (uploadFile.isEmpty() == false) {
            String originalFilename = uploadFile.getOriginalFilename();
            String compCode = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            Boolean isEncrypt = false;
            try {
                if (WebUtils.checkStr(request.getParameter("isEncrypt"))) {
                    isEncrypt = Boolean.valueOf(request.getParameter("isEncrypt"));
                }
                if (!uploadFile.isEmpty()) {
                    //拿出现在应用的文件存储方式
                    FileResource fileResource = fileResourceRepository.getByApplyResource("七牛存储");
                    String uploadImplClass = fileResource.getImplClassName();
                    FileUploadSaveService fileUploadSaveService = (FileUploadSaveService) Class.forName(String.valueOf(uploadImplClass)).getDeclaredConstructor().newInstance();
                    AttachFile attachFile = fileUploadSaveService.upload(attachFileRepository, uploadFile, fileResource, isEncrypt);
                    return WebUtils.flushObjSuccess(attachFile);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return WebUtils.flushFailure();
            }
        }

        return WebUtils.flushFailure();
    }

    @RequestMapping("del")
    @ResponseBody
    ReplyObj del(HttpServletRequest request, Company vo,
                 @RequestParam(defaultValue = "", required = false, value = "id") String id
    ) {
        try {
            companyRepository.deleteById(vo.getId());
            return WebUtils.flushSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure();
        }
    }


}
